#include <stdio.h>
#include <stdlib.h>
#include <algorithm>
#include <goat3dgfx/goat3dgfx.h>
#include <vmath/vmath.h>

using namespace goatgfx;

#define CUBEMAP_FILENAME	"data/cubemap2.jpg"

static bool init();
static void cleanup();
static void display();
static void skybox(const Texture *cubemap = 0);
static void reshape(int x, int y);
static void keyboard(unsigned char key, int x, int y);
static void mouse(int bn, int st, int x, int y);
static void motion(int x, int y);

static float cam_theta, cam_phi;

static Texture *cubemap;
static ShaderProg *sdrsky;

int main(int argc, char **argv)
{
	glutInit(&argc, argv);
	glutInitWindowSize(800, 600);
	glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE);
	glutCreateWindow("cubemap");

	glutDisplayFunc(display);
	glutReshapeFunc(reshape);
	glutKeyboardFunc(keyboard);
	glutMouseFunc(mouse);
	glutMotionFunc(motion);

	if(!init()) {
		return 1;
	}
	atexit(cleanup);

	glutMainLoop();
	return 0;
}

static bool init()
{
	glewInit();

	glEnable(GL_DEPTH_TEST);
	//glEnable(GL_CULL_FACE);

	cubemap = new Texture;
	if(!cubemap->load(CUBEMAP_FILENAME)) {
		fatal_log("Failed to load cubemap: %s\n", CUBEMAP_FILENAME);
		return false;
	}

	if(!(sdrsky = get_sdrprog("sdr/sky.v.glsl", "sdr/sky.p.glsl"))) {
		fatal_log("failed to load skybox shader\n");
		return false;
	}

	return true;
}

static void cleanup()
{
	delete cubemap;
}

static void display()
{
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	Matrix4x4 view_matrix;
	view_matrix.rotate(Vector3(1, 0, 0), M_PI * cam_phi / 180.0);
	view_matrix.rotate(Vector3(0, 1, 0), M_PI * cam_theta / 180.0);
	set_view_matrix(view_matrix);

	setup_gl_matrices();

	skybox(cubemap);

	glutSwapBuffers();
	CHECKGLERR;
}

static void skybox(const Texture *cubemap)
{
	static Mesh *skybox;

	if(!skybox) {
		skybox = new Mesh;
		gen_sphere(skybox, 10.0, 12, 6);
	}

	glPushAttrib(GL_ENABLE_BIT | GL_TEXTURE_BIT);
	glDisable(GL_DEPTH_TEST);
	glDisable(GL_CULL_FACE);
	glDisable(GL_LIGHTING);

	glEnable(GL_TEXTURE_CUBE_MAP);

	if(cubemap) cubemap->bind();
	sdrsky->bind();

	skybox->draw();

	glUseProgram(0);
	glPopAttrib();
}

static void reshape(int x, int y)
{
	glViewport(0, 0, x, y);

	Matrix4x4 proj;
	proj.set_perspective(M_PI / 4.0, (float)x / (float)y, 0.5, 500.0);
	set_projection_matrix(proj);
}

static void keyboard(unsigned char key, int x, int y)
{
	switch(key) {
	case 27:
		exit(0);
	}
}

static bool bnstate[16];
static int prev_x, prev_y;

static void mouse(int bn, int st, int x, int y)
{
	bnstate[bn - GLUT_LEFT_BUTTON] = st == GLUT_DOWN;
	prev_x = x;
	prev_y = y;
}

static void motion(int x, int y)
{
	int dx = x - prev_x;
	int dy = y - prev_y;
	prev_x = x;
	prev_y = y;

	if(!dx && !dy) return;

	if(bnstate[0]) {
		cam_theta += dx * 0.5;
		cam_phi += dy * 0.5;
		cam_phi = std::max(-90.0f, std::min(90.0f, cam_phi));
		glutPostRedisplay();
	}
}
